﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DragHandler : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler, IPointerEnterHandler, IPointerExitHandler {
	public static GameObject objectBeingDragged;
	static public Transform initialParent;
	Inventory inventory;
	Vector3 startPosition;
	void Start() {
		inventory = GameObject.FindGameObjectWithTag("StateManager").GetComponent<Inventory>();
	}
	#region IDragHandler implementation

	public void OnDrag (PointerEventData eventData){
		transform.position = ((Vector3)eventData.position + new Vector3(0,0,-10));
	}

	#endregion

	#region IEndDragHandler implementation

	public void OnEndDrag (PointerEventData eventData){
		objectBeingDragged = null;
		transform.position = startPosition;
		if (transform.parent.name == "Handler")
			transform.SetParent (initialParent);
		transform.parent.GetComponent<GridLayoutGroup>().enabled = true;
		GetComponent<CanvasGroup>().blocksRaycasts = true;
	}

	#endregion

	#region IBeginDragHandler implementation

	public void OnBeginDrag (PointerEventData eventData){
		objectBeingDragged = gameObject;
		initialParent = transform.parent;
		startPosition = transform.position;
		transform.parent.GetComponent<GridLayoutGroup>().enabled = false;
		transform.SetParent(transform.parent.parent);
		GetComponent<CanvasGroup>().blocksRaycasts = false;
	}

	#endregion

	#region IPointerEnterHandler implementation

	public void OnPointerEnter (PointerEventData eventData)
	{
		inventory.UpdateText(gameObject);
	}

	#endregion

	#region IPointerExitHandler implementation

	public void OnPointerExit (PointerEventData eventData)
	{
		inventory.UpdateText(null);
	}

	#endregion
}
